package com.bto.solar.work.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bto.solar.work.dto.order.DesignDto;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class WrappersFactory {

    private final static List<String> removeList = new ArrayList<>();

    static {
        removeList.add("createTime");
        removeList.add("updateTime");
        removeList.add("deleted");
    }

    public static <T> Set<String> setIgnoreList(Class<T> entity) {
        Set<String> ignoreList = new HashSet<>();
        List<Field> allFields = TableInfoHelper.getAllFields(entity);
        for (Field field : allFields) {
            if (removeList.contains(field.getName())) {
                continue;
            }
            ignoreList.add(field.getName());
        }
        return ignoreList;
    }

    public static <T> Set<String> setIgnoreList(Class<T> entity, Set<String> removeListBySet) {
        Set<String> ignoreList = new HashSet<>();
        Set<String> removeListByNew = new HashSet<>();
        removeListByNew.addAll(removeListBySet);
        removeListByNew.addAll(removeList);
        List<Field> allFields = TableInfoHelper.getAllFields(entity);
        for (Field field : allFields) {
            if (removeListByNew.contains(field.getName())) {
                continue;
            }
            ignoreList.add(field.getName());
        }
        return ignoreList;
    }

    public static <T> LambdaUpdateWrapper<T> updateWithNullField(T entity,  Set<String> ignoreList) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        List<Field> allFields = TableInfoHelper.getAllFields(entity.getClass());
        MetaObject metaObject = SystemMetaObject.forObject(entity);
        for (Field field : allFields) {
            if (ignoreList.contains(field.getName())) {
                Object value = metaObject.getValue(field.getName());
                //针对初设评审
                if ("designDevice".equals(field.getName())) {
                    value = JSON.toJSONString(value);
                }
                updateWrapper.set(StringUtils.camelToUnderline(field.getName()), value);
            }
        }
        return updateWrapper.lambda();
    }

}